// fetch请求封装
import 'whatwg-fetch'
import 'es6-promise'
// import { message } from 'antd'
/**
 * 将对象转成 a=1&b=2的形式
 * @param obj 对象
 */
import {  message } from "antd"
function obj2String(obj, arr = [], idx = 0) {
  for (let item in obj) {
    arr[idx++] = [item, obj[item]]
  }
  return new URLSearchParams(arr).toString()
}
/**
 * 请求封装
 * @param url 请求地址
 * @param params 请求参数
 * @param method 请求方式
 */

export default ({ url, params, method = 'GET' }) => {
  return new Promise((resolve, reject) => {
    let token=localStorage.getItem("token")

    const searchStr = obj2String(params)
    let initObj = {
      method: method,
      credentials: 'include',
      headers: new Headers({
        Accept: 'application/json',
        'Content-Type': 'application/x-www-form-urlencoded',
        token:token?token:''
      }),
    }
    if (method === 'GET') {
      // GET请求，拼接url
      url += '?' + searchStr
    } else {
      // POST请求，请求配置
      initObj = {
        ...initObj,
        ...{
       
          body: searchStr,
        },
      }
    
    }
    fetch(url, initObj)
      .then((res) => res.json())
      .then((res) => {
        if (res.status === 200) {
          resolve(res)
        }else {
          let mesg = ''
          switch (res.status) {
            case 1001:
              mesg = "帐号密码错误，请重新输入！";
              break;
            case 201:
              mesg = "请求错误";
              break;
            case 400:
              mesg = "请求错误";
              break;
            case 401:
              mesg = "请求错误";
              break;
            case 404:
              mesg = "请求地址出错";
              break;
            case 408:
              mesg = "请求超时";
              break;
            case 500:
              mesg = "服务器内部错误!";
              break;
            case 501:
              mesg = "服务未实现!";
              break;
            case 502:
              mesg = "网关错误!";
              break;
            case 503:
              mesg = "服务不可用!";
              break;
            case 504:
              mesg = "网关超时!";
              break;
            case 505:
              mesg = "HTTP版本不受支持";
              break;
          }
          message.error(mesg);
        }
        // 响应状态码校验
      })
  })
}
